package cn.iocoder.yudao.framework.tracer.core.util;

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;

import java.io.PrintWriter;
import java.io.StringWriter;


/**
 * 链路追踪 Util
 *
 * @author 芋道源码
 */
public class TracerFrameworkUtils {

    /**
     * 将异常记录到 Span 中，参考自 com.aliyuncs.utils.TraceUtils
     *
     * @param throwable 异常
     * @param span Span
     */
    public static void onError(Throwable throwable, Span span) {
        if (span == null || !span.getSpanContext().isValid()) {
            return;
        }
        if (throwable != null) {
            // 记录异常信息
            span.recordException(throwable);
            span.setStatus(StatusCode.ERROR, throwable.getMessage());

            // 如果需要，可以把完整堆栈放到属性里
            StringWriter sw = new StringWriter();
            throwable.printStackTrace(new PrintWriter(sw));
            span.setAttribute("error.stacktrace", sw.toString());
        } else {
            span.setStatus(StatusCode.ERROR);
        }
    }

}
